package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.Result;
import com.itheima.service.MemberService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/10/11 20:33
 */
@Controller
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    //运营数据统计折线图;
    @RequestMapping("/getMemberReport")
    @ResponseBody
    public Result getMemberReport() {
        //months
        Map map = new HashMap();
        List<String> monthsList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -13);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date months = calendar.getTime();
            monthsList.add(new SimpleDateFormat("yyyy-MM").format(months));
        }

        map.put("months", monthsList);
        List<Long> memberCount = memberService.findCountByMonths(monthsList);

        map.put("memberCount", memberCount);
        return new Result(true, "查询成功", map);
    }


    //运营数据统计分析;
    @RequestMapping("/getBusinessReportData")
    @ResponseBody
    public Result getBusinessReportData() {
        try {
            Map map = memberService.getBusinessReportData();
            map.put("reportDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            return new Result(true, "查询成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败");
        }
    }


    //统计会员的男女比例;
    @RequestMapping("genderCount")
    @ResponseBody
    public Result genderCount() {
        try {
            Map map = memberService.genderCount();
            return new Result(true, "查询会员性别数据成功", map);
        } catch (Exception e) {
            return new Result(false, "查询会员性别数据失败");
        }
    }

    //套餐预约占比;
    @RequestMapping("/getSetmealReport")
    @ResponseBody
    public Result getSetmealReport() {
        //setmealList
        //setmealCountList
        try {
            Map map = memberService.getSetmealReport();
            return new Result(true, "查询成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询失败");
        }
    }

    //excel文件下载
    @RequestMapping("/exportExcel")
    public void exportBusinessReport(HttpSession session, HttpServletResponse response) {
        try {
            //1.读取 /template/report_template.xlsx文件
            String path = session.getServletContext().getRealPath("/") + "template/report_business.xlsx";
            //2.根据读到的文件创建一个工作簿
            XSSFWorkbook workbook = new XSSFWorkbook(path);
            //3.从工作簿中获取第一个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);
            //4.调用Service查询导出的数据
            Map map = memberService.getBusinessReportData();
            //5.安装模板的内容，将指定的数据设定到指定的位置 workbook
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sheet.getRow(2).getCell(5).setCellValue(sdf.format(new Date()));//日期
            sheet.getRow(4).getCell(5).setCellValue(map.get("todayNewMember").toString()); //新增会员数
            sheet.getRow(4).getCell(7).setCellValue(map.get("totalMember").toString()); //总员数
            sheet.getRow(5).getCell(5).setCellValue(map.get("thisWeekNewMember").toString());
            sheet.getRow(5).getCell(7).setCellValue(map.get("thisMonthNewMember").toString());

            sheet.getRow(7).getCell(5).setCellValue(map.get("todayOrderNumber").toString());
            sheet.getRow(7).getCell(7).setCellValue(map.get("todayVisitsNumber").toString());
            sheet.getRow(8).getCell(5).setCellValue(map.get("thisWeekOrderNumber").toString());
            sheet.getRow(8).getCell(7).setCellValue(map.get("thisWeekVisitsNumber").toString());
            sheet.getRow(9).getCell(5).setCellValue(map.get("thisMonthOrderNumber").toString());
            sheet.getRow(9).getCell(7).setCellValue(map.get("thisMonthVisitsNumber").toString());

            List<Map> setmealList = (List<Map>) map.get("setmealList");
            if (setmealList != null && setmealList.size() > 0) {
                for (int i = 0; i < setmealList.size(); i++) {
                    Map temp = setmealList.get(i);
                    Row row = sheet.getRow(12 + i);
                    row.getCell(4).setCellValue(temp.get("name").toString());
                    row.getCell(5).setCellValue(temp.get("value").toString());
                    String per = temp.get("per").toString();
                    Double perDf = Double.parseDouble(per) * 100;
                    row.getCell(6).setCellValue(perDf + "%");
                    row.getCell(7).setCellValue(temp.get("remark").toString());
                }
            }
            //解决导出的excel中名称有中文的问题;
            String filename = new String(("运营数据统计" + sdf.format(new Date()) + ".xlsx").getBytes(),"ISO8859-1");

            //两个头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;chartset=utf-8"); //xlsx 的MIMETYPE
            response.setHeader("Content-Disposition", "attachment;fileName="+filename);
            //一个流
            ServletOutputStream outputStream = response.getOutputStream();
            //6.把Excel输出成一个流返回到前端
            workbook.write(outputStream);
            //7.关闭资源
            outputStream.close();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
